package pl.edu.pw.MidEmu.Common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * Helper class used for fast files copying
 * @author Mateusz Starodab
 *
 */
public class CopyManager
{
	/**
	 * Method copies file
	 * @param source Source file path
	 * @param target Target path
	 */
	public static void copyFile(File source, File target)
	{
		FileInputStream sourceStream = null;
		FileOutputStream targetStream = null;
		try
		{
			sourceStream = new FileInputStream(source);
			targetStream = new FileOutputStream(target);

			FileChannel sourceChannel = sourceStream.getChannel();
			FileChannel targetChannel = targetStream.getChannel();

			sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);

			sourceChannel.close();
			targetChannel.close();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (sourceStream != null)
					sourceStream.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			try
			{

				if (targetStream != null)
					targetStream.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * Recursively copies files contained in directory 
	 * @param strPath Source path
	 * @param dstPath Destination path
	 */
	public static void copyFiles(String strPath, String dstPath)
	{
		File src = new File(strPath);
		File dest = new File(dstPath);

		if (src.isDirectory())
		{
			if (dest.mkdirs())
			{
				String list[] = src.list();

				for (String file : list)
				{
					String dest1 = dstPath + File.separatorChar + file;
					String src1 = strPath + File.separatorChar + file;
					copyFiles(src1, dest1);
				}
			}
			else
				return;
		}
		else
			copyFile(src, dest);
	}
}
